package org.start.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;

public class Client {

    public static Socket connect(String host, int port) {
        try {
            // 创建客户端Socket，指定服务器地址和端口
            Socket socket = new Socket(host, port);
            socket.setSoTimeout(60000);
            return socket;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void handleClient(Socket socket) throws IOException {
        while (true) {
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            DataInputStream dis = new DataInputStream(socket.getInputStream());

            // 根据终端的输入的字符串发送到服务器
            Scanner sc = new Scanner(System.in);
            System.out.print("send:  ");
            String msg = sc.nextLine();
            dos.writeUTF(msg);

            String res = dis.readUTF();
            if ("exit".equals(res)) {
                System.out.println("client exit");
                break;
            } else {
                System.out.println(res);
            }
        }
    }

    public static void main(String[] args) {
        if (args.length <= 1) {
            return;
        }

        String host = args[0];
        try {
            int port = Integer.parseInt(args[1]);
            Socket socket = connect(host, port);
            if (socket != null) {
                System.out.println("Connect success at " + socket.getRemoteSocketAddress());
                handleClient(socket);

            } else {
                System.out.println("Connect failed");
            }
        } catch (SocketException e) {
            System.out.println("Server start timeout");
        } catch (IOException e) {
            System.out.println("Connect failed");
            e.printStackTrace();
        }

    }
}
